package com.guanghua.brick.html.tag;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.guanghua.brick.html.IContent;
import com.guanghua.brick.html.IControl;

public class ContentBeanTag extends BodyTagSupport {
	
	private static Log logger = LogFactory.getLog(ContentBeanTag.class);

	private String bean = null;
	private String id = null;
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = ContentConfigTag.getPagePrefix((HttpServletRequest)pageContext.getRequest(), id);
	}
	public String getBean() {
		return bean;
	}
	public void setBean(String bean) {
		this.bean = bean;
	}
	
	public int doEndTag() throws JspException {
		if (bean != null) { 	
			//获取content pool，并将content放入
			Map<String, IContent> pool = ContentConfigTag.getContentPool(pageContext.getServletContext());
			
			try {
				//生成content实例
				IContent content = (IContent)Class.forName(bean).newInstance();
				content.setId(this.id);
				pool.put(content.getId(), content);
				logger.trace("content id: " + content.getId());
				logger.trace("content cls: " + content.toString());
				
				//设置父控件中的content属性
				Tag parent = this.getParent();
				if (parent instanceof IControl) {
					((IControl)parent).setContent(content);
				}
			} catch (InstantiationException e) {
				logger.error("class init error:"+bean, e);
			} catch (IllegalAccessException e) {
				logger.error("class access error:"+bean, e);
			} catch (ClassNotFoundException e) {
				logger.error("not found class:"+bean, e);
			}
			
		}
		return BodyTagSupport.EVAL_PAGE;
	}
	
}
